package com.example.gzysmartcity.ui.fragment.me;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.gzysmartcity.R;
import com.example.gzysmartcity.databinding.FragmentCommitBinding;
import com.example.gzysmartcity.repository.model.Opinion;
import com.example.gzysmartcity.ui.adapter.CommitImageAdapter;
import com.example.gzysmartcity.ui.base.BaseFragment;
import com.example.gzysmartcity.utils.PopupUntil;
import com.example.gzysmartcity.viewmodel.HistoryViewModel;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class CommitFragment extends BaseFragment<FragmentCommitBinding> {
    private final List<String> imagesUri = new ArrayList<>();
    private CommitImageAdapter adapter;
    private final int ACTION_IMAGE_CAPTURE = 1;
    private final int ACTION_PICK = 11;
    private HistoryViewModel mHistoryViewModel;
    private String imgName;

    @Override
    protected FragmentCommitBinding viewBinding() {
        return FragmentCommitBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mHistoryViewModel = new ViewModelProvider(this).get(HistoryViewModel.class);
        b.tvHistorycom.setOnClickListener(v -> jump(HistoryFragment.class, null, null));
        b.editCommit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                b.tvCommitIndex.setText(s.length() + "/500");
            }
        });
        b.rvCommit.setLayoutManager(new GridLayoutManager(getContext(), 3));
        adapter = new CommitImageAdapter(R.layout.rv_commit_item);
        b.rvCommit.setAdapter(adapter);
        imagesUri.add("");
        adapter.setNewInstance(imagesUri);
        //拍照相册选择
        adapter.setOnItemClickListener((adapter, view1, position) -> {
            if (imagesUri.size() == 6) {
                ToastUtils.showShort("最多只能添加5张图片");
                return;
            }
            if (position == 0) {
                PopupUntil popupUntil = new PopupUntil();
                View viewP = popupUntil.getPopupDataByLayId(R.layout.popu_commit_xc_pz, requireContext());
                TextView pPhoto = viewP.findViewById(R.id.popu_picture);
                TextView popupCancel = viewP.findViewById(R.id.popu_cancel);
                TextView popupPicture = viewP.findViewById(R.id.popu_xiangce);
                popupCancel.setOnClickListener(v -> popupUntil.closePopup());
                pPhoto.setOnClickListener(v -> {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File fileDir = new File(Environment.getExternalStorageDirectory(), "Pictures");
                    if (!fileDir.exists()) {
                        fileDir.mkdir();
                    }
                    imgName = "IMG_" + System.currentTimeMillis() + ".jpg";
                    String fileName = fileDir.getAbsolutePath() + "/" + imgName;
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, imgName);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "DCIM/Pictures");
                    } else {
                        contentValues.put(MediaStore.Images.Media.DATA, fileName);
                    }
                    contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG");
                    Uri uri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

                    try {
                        startActivityForResult(intent, ACTION_IMAGE_CAPTURE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort("此设备没有摄像机");
                    }

                });
                popupPicture.setOnClickListener(v -> {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    try {
                        startActivityForResult(intent, ACTION_PICK);
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort("此设备没有图库");
                    }
                });

            }
        });
        //提交
        b.btnCommit.setOnClickListener(v -> {
            String tel = b.editPhone.getText().toString().trim();
            String content = b.editCommit.getText().toString().trim();
            long time = TimeUtils.getNowMills();
            if (RegexUtils.isMobileSimple(tel) || RegexUtils.isTel(tel)) {
                if (content.length() != 0) {
                    //第一个为添加图标
                    imagesUri.remove(0);
                    mHistoryViewModel.insertOpinion(new Opinion(Long.parseLong(tel), content, time, imagesUri));
                    b.editCommit.setText("");
                    b.editPhone.setText("");
                    imagesUri.clear();
                    adapter.notifyDataSetChanged();
                    imagesUri.add("");
                    b.tvPictureIndex.setText("0/5");
                    ToastUtils.showShort("保存成功");
                } else {
                    ToastUtils.showShort("内容未填");
                }
            } else {
                ToastUtils.showShort("联系人电话不正确");
            }
        });

    }

    @SuppressLint({"Range", "SetTextI18n"})
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ACTION_PICK://相片
                if (data == null) return;
                Cursor cursor = requireContext().getContentResolver().query(data.getData(), new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                cursor.moveToFirst();
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                imagesUri.add(path);
                Log.i("TAG", "onActivityResult: " + path);
                adapter.notifyItemInserted(imagesUri.size() - 1);
                b.tvPictureIndex.setText(imagesUri.size() - 1 + "/5");
                cursor.close();
                break;
            case ACTION_IMAGE_CAPTURE://拍照
                //拍照完成会返回-1，未拍照直接返回会返回0
                Log.i("TAG", "onActivityResult: " + resultCode);
                try {
                    //查询的条件语句
                    String selection = MediaStore.Images.Media.DISPLAY_NAME + "=? ";
                    //查询的sql
                    //Uri：指向外部存储Uri
                    //projection：查询那些结果
                    //selection：查询的where条件
                    //sortOrder：排序
                    Cursor cursor2 = requireContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media.DATA}, selection, new String[]{imgName}, null);
                    if (cursor2 != null && cursor2.moveToFirst()) {
                        cursor2.moveToFirst();
                        String path2 = cursor2.getString(cursor2.getColumnIndex(MediaStore.Images.Media.DATA));
                        Log.i("TAG", "path2: " + path2);
                        imagesUri.add(path2);
                        cursor2.close();
                    }
                } catch (Exception e) {
                    ToastUtils.showShort(e.toString());
                    e.printStackTrace();
                }
                imgName = "";
                adapter.notifyItemInserted(imagesUri.size() - 1);
                b.tvPictureIndex.setText(imagesUri.size() - 1 + "/5");
                break;
        }
    }

    @Override
    protected String setTitle() {
        return "提交意见";
    }

    @Override
    protected boolean showBack() {
        return true;
    }

    @Override
    protected Boolean showBottom() {
        return false;
    }
}
